package com.sgb.kjwl.viewmodel.self.packers;

import android.view.Gravity;
import android.view.View;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamMemberEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamMemberEditActivity;
import com.sgb.kjwl.view.widget.TeamWorkTypePopWindow;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 * @author WYJ
 * @date 2020/8/12
 */
public class SelfTeamMemberEditModel extends BaseViewModel implements TeamWorkTypePopWindow.FilterResultClick, TeamWorkTypePopWindow.IItemClick {

    private SelfTeamMemberEditActivity mActivity;

    private TeamWorkTypePopWindow mPopWindow;
    private List<PickSelectEntity> mWorkTypes = new ArrayList<>();

    public SelfTeamMemberEditModel(SelfTeamMemberEditActivity mActivity, SelfRepertory mRepertory) {
        this.mActivity = mActivity;
    }

    /**
     * 工种
     */
    public void getWorkType() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getTeamPriceAPI().getWorkType().
                enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() != null && response.body().getState() != null && response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            updateWorkTypePopup(response.body().getData());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    /**
     * 工种
     * @param data
     */
    private void updateWorkTypePopup(List<PickSelectEntity> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        mWorkTypes.addAll(data);
        if (mPopWindow == null) {
            //初始化筛选
            mPopWindow = new TeamWorkTypePopWindow(mActivity);
            mPopWindow.setFilterResultClick(this);
            mPopWindow.onItemClick(this);
        }
        mPopWindow.setData1(mWorkTypes);
    }

    public void showPop(View view) {
        if (mPopWindow == null) {
            getWorkType();
        } else {
            if (!mPopWindow.isShowing()) {
                mPopWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        }
    }

    @Override
    public void result(PickSelectEntity... entity) {
        if (entity.length > 0) {
            mActivity.setWorkTypeFilter(entity[0]);
        }
    }

    @Override
    public void itemClick(String firstNo, int position, String name) {

    }

    public void pictureSelector(int number, int requestCode) {
        PictureSelector.create(mActivity)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.MULTIPLE)
                .compress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .maxSelectNum(number)//判断还能选多少张图片
                .forResult(requestCode);
    }

    //上传头像
    public void uploadAvatarFileModel(File file, int completeNum) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(mActivity, null, "头像上传中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null || response.body().getState() == null) {
                    MToast.showToast(mActivity, "上传失败！");
                    DialogHelper.dismissProgressDialog();
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.uploadAvatarResult(response.body().getData().toString());
                } else {
                    MToast.showToast(mActivity, "上传失败！");
                    DialogHelper.dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, "上传失败！" + t.getMessage());
            }
        });
    }

    //上传多图片
    public void uploadMultiFileModel(File file, int completeNum, int imgTotal,boolean isPerformance) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(mActivity, null, "图片上传中" + completeNum + "/" + imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null || response.body().getState() == null) {
                    MToast.showToast(mActivity, "上传失败！");
                    DialogHelper.dismissProgressDialog();
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.uploadRefresh(file.getAbsolutePath(), response.body().getData().toString(),isPerformance);
                } else {
                    MToast.showToast(mActivity, "上传失败！");
                    DialogHelper.dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, "上传失败！" + t.getMessage());
            }
        });
    }

    public void addTeamMember(SelfTeamMemberEntity entity) {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().addTeamMember(entity).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
                DialogHelper.dismissProgressDialog();
                BaseEntity<Object> body = response.body();
                if (body == null || body.getState() == null) {
                    MToast.showToast(mActivity, "发布失败！");
                    return;
                }
                if (body.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.editEntitySuccess();
                } else {
                    MToast.showToast(mActivity, body.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, t.getMessage());
            }
        });
    }

    public void detailTeamMember(SelfTeamMemberEntity entity) {
        Map<String,Object> map = new HashMap<>();
        map.put("no",entity.getNo());
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().detailTeamMember(map).enqueue(new Callback<BaseEntity<SelfTeamMemberEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<SelfTeamMemberEntity>> call, Response<BaseEntity<SelfTeamMemberEntity>> response) {
                DialogHelper.dismissProgressDialog();
                BaseEntity<SelfTeamMemberEntity> body = response.body();
                if (body == null || body.getState() == null) {
                    mActivity.showEmpty();
                    return;
                }
                if (body.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.updateOfferEntity(body.getData());
                } else {
                    MToast.showToast(mActivity, body.getMsg());
                    mActivity.showEmpty();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<SelfTeamMemberEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, t.getMessage());
                mActivity.showEmpty();
            }
        });
    }

    private OptionsPickerView<PickSelectEntity> mCityOptions;//地址选择器
    private List<PickSelectEntity<List<PickSelectEntity>>> mOpt;
    private List<PickSelectEntity> mOpt1 = new ArrayList<>();//省
    private List<List<PickSelectEntity>> mOpt2 = new ArrayList<>();//市
    private int opt1;
    private int opt2;

    public void getCityData(boolean isShow) {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getLocateList().enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getCode().equals("200")) {
                    mOpt = response.body().getData();
                    if (mOpt == null || mOpt.size() == 0) {
                        return;
                    }
                    mOpt = response.body().getData();
                    mOpt1.clear();
                    mOpt1.addAll(mOpt);
                    mOpt2.clear();
                    for (PickSelectEntity<List<PickSelectEntity>> provinceDatum : mOpt) {
                        List<PickSelectEntity> children = provinceDatum.getChildren();
                        mOpt2.add(children);
                    }
                    if (isShow) {
                        showAddressPop();
                    }
                } else {
                    MToast.showToast(mActivity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void showAddressPop() {
        if (mOpt1 == null || mOpt1.size() == 0) {
            getCityData(true);
            return;
        }
        if (mCityOptions == null) {
            mCityOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mActivity.updateAddress(mOpt.get(options1), mOpt2.get(options1).get(options2));
                    opt1 = options1;
                    opt2 = options2;
                }
            }).build();
            mCityOptions.setTitleText("请选择籍贯");
        }
        mCityOptions.setPicker(mOpt1, mOpt2);
        mCityOptions.setSelectOptions(opt1, opt2);
        mCityOptions.show();
    }

    public void getNationRecord() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getNationRecord().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<PickSelectEntity> data = response.body().getData();
                    if (data == null || data.size() == 0) {
                        data = new ArrayList<>();
                    }
                    mActivity.showNationRecordPop(data);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
